package de.se.ludoapp.activity.task;

import android.content.Intent;
import android.os.AsyncTask;
import android.view.View;
import android.widget.Button;
import de.se.ludoapp.LudoApplication;
import de.se.ludoapp.R;
import de.se.ludoapp.activity.LoginRememberActivity;
import de.se.ludoapp.activity.Select_menuActivity;
import de.se.ludoapp.gaming.User;
import de.se.ludoapp.response.UserLoginResponse;

/**
 * Task for login and logout of the user in communication with the server.
 * 
 * @author L.Rother
 * 
 */
public class LoginLogoutRegisterTask extends AsyncTask<String, Integer, String> {

	private LudoApplication ludoApp;
	private LoginRememberActivity context;
	private String username;
	private String password;

	public LoginLogoutRegisterTask(LudoApplication ludoApp,
			LoginRememberActivity loginRememberActivity, String username,
			String password) {
		super();
		this.ludoApp = ludoApp;
		this.context = loginRememberActivity;
		this.username = username;
		this.password = password;
	}

	/**
	 * hadels login and logout with server. <br>
	 * This method is executed in a concurrent thread (asynchronous). Therefore
	 * you mustn't accessed on view elements!
	 */
	@Override
	protected String doInBackground(String... params) {
		String output = null;
		if (ludoApp.getlogedinUser() == null) {
			/* Execute Login */
			UserLoginResponse userLoginResponse = ludoApp.getLudoStub().login(
					username, password);
			if (userLoginResponse.hasResponseErrors()) {
				output = userLoginResponse.getMsg();
			} else {
				User logedinUser = new User(username, password,
						userLoginResponse.getSessionId());
				ludoApp.setLogedinUser(logedinUser);
				output = "Sie sind eingeloggt als " + logedinUser.getUsername();
			}

		} else {
			/* Execute Logout */
			ludoApp.getLudoStub().logout(ludoApp.getlogedinUser());
			ludoApp.setLogedinUser(null);
			output = "Bitte erneut einloggen";
		}
		return output;
	}

	/**
	 * show login/logout results. <br>
	 * This method is invoked when the LoginTask is executed. You are only
	 * allowed here to access on view Elements (TextView and Buttons)!
	 */
	@Override
	protected void onPostExecute(String result) {

		Button buttonLogin = (Button) context.findViewById(R.id.buttonRegLogin);
		buttonLogin.setEnabled(true);
		Button buttonMenue = (Button) context
				.findViewById(R.id.buttonMainMenueReg);
		if (ludoApp.getlogedinUser() == null) {
			buttonLogin.setText(R.string.buttonLogin);
			buttonMenue.setVisibility(View.GONE);
		} else {
			buttonLogin.setText(R.string.buttonLogout);
			Intent intentSelectMenu = new Intent(context,
					Select_menuActivity.class);
			context.startActivity(intentSelectMenu);
			buttonMenue.setVisibility(View.VISIBLE);
		}
	}

}
